package algorithm.offer;

/**
 * 单词翻转
 */
public class DanciFanZhuan {

    public static void main(String[] args) {
        String s = "the sky is blue";
        int l = s.length() - 1;
        int r = s.length() - 1;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = l; i >= 0; i--) {
            // 前指针到达临界区
            if ((s.charAt(i) != ' ' && i == 0) ||
                    (s.charAt(i) != ' ' && s.charAt(i - 1) == ' ')
            ) {
                for (int j = r; j >= 0; j--) {
                    if ((s.charAt(j) != ' ' && j == s.length() - 1) ||
                            (s.charAt(j) != ' ' && s.charAt(j + 1) == ' ')) {
                        stringBuilder.append(s.substring(i, j + 1)).append(" ");
                        r = j - 1;
                        break;
                    }
                }
            }
        }
        if (stringBuilder.length() > 0)
            stringBuilder.setLength(stringBuilder.length() - 1);
        System.out.println(stringBuilder);
    }

}
